package cn.zn.modules.zzsys.cur.service.impl;

import cn.zn.modules.zzsys.cur.entity.dto.SysPushSwitchSaveDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zn.modules.zzsys.cur.entity.SysPushSwitch;
import cn.zn.modules.zzsys.cur.service.SysPushSwitchService;
import cn.zn.modules.zzsys.cur.mapper.SysPushSwitchMapper;
import com.beust.jcommander.internal.Lists;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class SysPushSwitchServiceImpl extends ServiceImpl<SysPushSwitchMapper, SysPushSwitch>
        implements SysPushSwitchService {

    @Override
    public Boolean isOpen(String workNo) {
        SysPushSwitch sysPushSwitch = this.getOne(new QueryWrapper<SysPushSwitch>().eq("work_no", workNo));
        return sysPushSwitch == null || sysPushSwitch.getIsOpen().equals(new Byte("1"));
    }

    @Override
    public void save(SysPushSwitchSaveDTO dto) {
        Map<String, SysPushSwitch> map = this.list(new QueryWrapper<SysPushSwitch>().in("work_no", dto.getWorkNos()))
                .stream().collect(Collectors.toMap(SysPushSwitch::getWorkNo, o -> o));
        List<SysPushSwitch> newList = new ArrayList<>();
        List<SysPushSwitch> updateList = new ArrayList<>();
        dto.getWorkNos().forEach(o -> {
            Byte isOpen = dto.getIsOpen() ? new Byte("1") : new Byte("0");
            SysPushSwitch sysPushSwitch = null;
            if (map.containsKey(o)) {
                sysPushSwitch = map.get(o);
                sysPushSwitch.setIsOpen(isOpen);
                updateList.add(sysPushSwitch);
            } else {
                sysPushSwitch = new SysPushSwitch(o, isOpen);
                newList.add(sysPushSwitch);
            }
        });
        if (!updateList.isEmpty()) {
            this.updateBatchById(updateList);
        }
        if (!newList.isEmpty()) {
            this.saveBatch(newList);
        }
    }
}




